/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "led.h"
#include "mt6701.h"
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include "stm32f1xx_hal_adc.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;

SPI_HandleTypeDef hspi1;
DMA_HandleTypeDef hdma_spi1_rx;
DMA_HandleTypeDef hdma_spi1_tx;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */
// 电机控制相关变量
float current_a = 0.0f;    // 相电流A
float current_b = 0.0f;    // 相电流B
float current_c = 0.0f;    // 相电流C (通过A+B+C=0计算得到)

// Clark变换后的电流 (α-β坐标系)
float current_alpha = 0.0f;
float current_beta = 0.0f;

// Park变换后的电流 (d-q坐标系)
float current_d = 0.0f;
float current_q = 0.0f;

// 电机角度信息 (从编码器获取)
float motor_angle = 0.0f;

// 参考电流 (d-q坐标系)
float ref_current_d = 0.0f;
float ref_current_q = 0.0f;

// SVPWM相关变量
float voltage_alpha = 0.0f;  // α轴电压
float voltage_beta = 0.0f;   // β轴电压
float u_dc = 12.0f;          // DC母线电压 (根据实际电源调整)

// PWM占空比
float duty_a = 0.0f;
float duty_b = 0.0f;
float duty_c = 0.0f;

// 转换系数 (根据实际硬件调整)
#define CURRENT_CONV_FACTOR 0.001f  // 电流转换系数，将ADC读数转换为实际电流值
#define CLARK_PARK_SCALE 2.0f/3.0f  // Clark-Park变换的缩放因子
#define SVPWM_SCALE 2.0f/3.0f       // SVPWM缩放因子

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_SPI1_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_ADC2_Init(void);
/* USER CODE BEGIN PFP */
// ADC转换完成回调函数
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc);

// ADC注入转换完成回调函数
void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc);

// Clark变换：三相电流 -> α-β坐标系
void clark_transform(float ia, float ib, float ic, float *ialpha, float *ibeta);

// Park变换：α-β坐标系 -> d-q坐标系
void park_transform(float ialpha, float ibeta, float theta, float *id, float *iq);

// 逆Park变换：d-q坐标系 -> α-β坐标系
void inverse_park_transform(float id, float iq, float theta, float *ialpha, float *ibeta);

// PI控制器
float pi_controller(float setpoint, float feedback, float kp, float ki, float *integral, float max_output);

// SVPWM生成
void svpwm_generate(float u_alpha, float u_beta, float u_dc, float *duty_a, float *duty_b, float *duty_c);

// 电机控制主函数
void motor_control_loop(void);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// 调试计数�???
uint16_t debug_counter = 0;

// 重定向printf到USART2
int fputc(int ch, FILE *f)
{
  HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF);
  return ch;
}

// 可�?�：重定向scanf从USART2读取
int fgetc(FILE *f)
{
  uint8_t ch = 0;
  HAL_UART_Receive(&huart2, &ch, 1, 0xFFFF);
  return ch;
}

// Clark变换：三相电流 -> α-β坐标系
void clark_transform(float ia, float ib, float ic, float *ialpha, float *ibeta)
{
  // 使用两电流Clark变换公式 (ic = -ia - ib)
  *ialpha = ia;
  *ibeta = (ia + 2 * ib) * (1.0f / sqrtf(3.0f));
  
  // 应用缩放因子
  *ialpha *= CLARK_PARK_SCALE;
  *ibeta *= CLARK_PARK_SCALE;
}

// Park变换：α-β坐标系 -> d-q坐标系
void park_transform(float ialpha, float ibeta, float theta, float *id, float *iq)
{
  float cos_theta = cosf(theta);
  float sin_theta = sinf(theta);
  
  *id = ialpha * cos_theta + ibeta * sin_theta;
  *iq = -ialpha * sin_theta + ibeta * cos_theta;
}

// 逆Park变换：d-q坐标系 -> α-β坐标系
void inverse_park_transform(float id, float iq, float theta, float *ialpha, float *ibeta)
{
  float cos_theta = cosf(theta);
  float sin_theta = sinf(theta);
  
  *ialpha = id * cos_theta - iq * sin_theta;
  *ibeta = id * sin_theta + iq * cos_theta;
}

// PI控制器
float pi_controller(float setpoint, float feedback, float kp, float ki, float *integral, float max_output)
{
  float error = setpoint - feedback;
  
  // 积分项计算
  *integral += ki * error;
  
  // 积分限幅
  if (*integral > max_output) *integral = max_output;
  if (*integral < -max_output) *integral = -max_output;
  
  // 计算输出
  float output = kp * error + *integral;
  
  // 输出限幅
  if (output > max_output) output = max_output;
  if (output < -max_output) output = -max_output;
  
  return output;
}

// SVPWM生成
void svpwm_generate(float u_alpha, float u_beta, float u_dc, float *duty_a, float *duty_b, float *duty_c)
{
  float t1, t2, t0;  // 矢量作用时间
  int sector;        // 扇区
  
  // 计算扇区
  float u_beta_prime = u_beta;
  float u_alpha_prime = u_alpha * 2.0f / 3.0f;
  float u0 = u_dc / 2.0f;  // 参考零矢量
  
  float v1 = u_beta_prime;
  float v2 = (sqrtf(3.0f) * u_alpha_prime - u_beta_prime) / 2.0f;
  float v3 = (-sqrtf(3.0f) * u_alpha_prime - u_beta_prime) / 2.0f;
  
  // 确定扇区
  int n = 0;
  if (v2 > 0) n += 1;
  if (v3 > 0) n += 2;
  if (v1 > 0) n += 4;
  
  switch (n) {
    case 5: sector = 1; break;
    case 1: sector = 2; break;
    case 3: sector = 3; break;
    case 2: sector = 4; break;
    case 6: sector = 5; break;
    case 4: sector = 6; break;
    default: sector = 1; break;
  }
  
  // 计算基本矢量作用时间
  float tmp = sqrtf(3.0f) * u_dc;
  t1 = (sqrtf(3.0f) * u_beta) / tmp;
  t2 = (3.0f * u_alpha + sqrtf(3.0f) * u_beta) / (2.0f * tmp);
  
  // 计算零矢量作用时间
  t0 = 1.0f - t1 - t2;
  
  // 根据扇区计算各相占空比
  switch (sector) {
    case 1:
      *duty_a = (1.0f - t1 - t2) / 2.0f;
      *duty_b = (1.0f + t1) / 2.0f;
      *duty_c = (1.0f + t1 + t2) / 2.0f;
      break;
    case 2:
      *duty_a = (1.0f - t2) / 2.0f;
      *duty_b = (1.0f + t2 + t1) / 2.0f;
      *duty_c = (1.0f + t1) / 2.0f;
      break;
    case 3:
      *duty_a = (1.0f - t1 - t2) / 2.0f;
      *duty_b = (1.0f - t1) / 2.0f;
      *duty_c = (1.0f + t2) / 2.0f;
      break;
    case 4:
      *duty_a = (1.0f + t2) / 2.0f;
      *duty_b = (1.0f - t1 - t2) / 2.0f;
      *duty_c = (1.0f - t1) / 2.0f;
      break;
    case 5:
      *duty_a = (1.0f + t1 + t2) / 2.0f;
      *duty_b = (1.0f - t2) / 2.0f;
      *duty_c = (1.0f - t1 - t2) / 2.0f;
      break;
    case 6:
      *duty_a = (1.0f + t1) / 2.0f;
      *duty_b = (1.0f + t1 + t2) / 2.0f;
      *duty_c = (1.0f - t2) / 2.0f;
      break;
    default:
      *duty_a = 0.5f;
      *duty_b = 0.5f;
      *duty_c = 0.5f;
      break;
  }
}

// PI控制器积分项
static float id_integral = 0.0f;
static float iq_integral = 0.0f;

// 电机控制主函数
void motor_control_loop(void)
{
  // PI控制器参数 (需要根据实际电机调整)
  float kp_id = 0.1f;  // d轴电流环比例系数
  float ki_id = 0.01f; // d轴电流环积分系数
  float kp_iq = 0.1f;  // q轴电流环比例系数
  float ki_iq = 0.01f; // q轴电流环积分系数
  float max_voltage = u_dc * 0.5f;  // 最大电压限幅
  
  // 电流环PI控制
  float voltage_d = pi_controller(ref_current_d, current_d, kp_id, ki_id, &id_integral, max_voltage);
  float voltage_q = pi_controller(ref_current_q, current_q, kp_iq, ki_iq, &iq_integral, max_voltage);
  
  // 逆Park变换，得到α-β坐标系下的电压
  inverse_park_transform(voltage_d, voltage_q, motor_angle, &voltage_alpha, &voltage_beta);
  
  // 生成SVPWM信号
  svpwm_generate(voltage_alpha, voltage_beta, u_dc, &duty_a, &duty_b, &duty_c);
  
  // TODO: 将计算得到的占空比应用到PWM输出
  // 这里需要根据实际硬件配置，使用HAL_PWM_ConfigChannel和HAL_PWM_Start等函数
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_SPI1_Init();
  MX_USART2_UART_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  /* USER CODE BEGIN 2 */
  LED_Init();
  MT6701_Init(&hspi1);
  MT6701_StartReading(); // 在初始化后手动启动MT6701数据接收
  // ADC校准操作，提高测量精度
  HAL_ADCEx_Calibration_Start(&hadc1); // 启动ADC1校准
  HAL_ADCEx_Calibration_Start(&hadc2); // 启动ADC2校准
  // 启动ADC注入通道转换(均使用中断方式)
  HAL_ADCEx_InjectedStart_IT(&hadc1); // 启动ADC1注入通道转换(带中断)
  HAL_ADCEx_InjectedStart_IT(&hadc2); // 启动ADC2注入通道转换(带中断)
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    // LED闪烁
    LED_Blink(500);
    
    // 打印MT6701角度信息
    float current_angle = MT6701_GetAngle();
    printf("MT6701 Angle: %.2f degrees\n", current_angle);
    
    // 更新电机角度值
    motor_angle = current_angle * M_PI / 180.0f;  // 转换为弧度
    
    // 打印电机控制相关参数
    debug_counter++;
    if (debug_counter % 100 == 0) {  // 定期打印，避免输出过快
      printf("\n----- Motor Control Data -----\n");
      printf("Three-phase Current: Ia=%.2f mA, Ib=%.2f mA, Ic=%.2f mA\n", current_a, current_b, current_c);
      printf("Alpha-Beta Current: Iα=%.2f mA, Iβ=%.2f mA\n", current_alpha, current_beta);
      printf("D-Q Current: Id=%.2f mA, Iq=%.2f mA\n", current_d, current_q);
      printf("Reference Current: Ref_Id=%.2f mA, Ref_Iq=%.2f mA\n", ref_current_d, ref_current_q);
      printf("Alpha-Beta Voltage: Vα=%.2f, Vβ=%.2f\n", voltage_alpha, voltage_beta);
      printf("PWM Duty Cycle: Da=%.4f, Db=%.4f, Dc=%.4f\n", duty_a, duty_b, duty_c);
      printf("-------------------------------\n");
      debug_counter = 0;
    }
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV2;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief ADC1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  ADC_ChannelConfTypeDef sConfig = {0};
  ADC_InjectionConfTypeDef sConfigInjected = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */
  /** Common config
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_0;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Injected Channel
  */
  sConfigInjected.InjectedChannel = ADC_CHANNEL_0;
  sConfigInjected.InjectedRank = ADC_INJECTED_RANK_1;
  sConfigInjected.InjectedNbrOfConversion = 1;
  sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
  sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T1_CC4;
  sConfigInjected.AutoInjectedConv = DISABLE;
  sConfigInjected.InjectedDiscontinuousConvMode = DISABLE;
  sConfigInjected.InjectedOffset = 0;
  if (HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}

/**
  * @brief ADC2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC2_Init(void)
{

  /* USER CODE BEGIN ADC2_Init 0 */

  /* USER CODE END ADC2_Init 0 */

  ADC_ChannelConfTypeDef sConfig = {0};
  ADC_InjectionConfTypeDef sConfigInjected = {0};

  /* USER CODE BEGIN ADC2_Init 1 */

  /* USER CODE END ADC2_Init 1 */
  /** Common config
  */
  hadc2.Instance = ADC2;
  hadc2.Init.ScanConvMode = ADC_SCAN_DISABLE;
  hadc2.Init.ContinuousConvMode = DISABLE;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.NbrOfConversion = 1;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_1;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Injected Channel
  */
  sConfigInjected.InjectedChannel = ADC_CHANNEL_1;
  sConfigInjected.InjectedRank = ADC_INJECTED_RANK_1;
  sConfigInjected.InjectedNbrOfConversion = 1;
  sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
  sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T1_CC4;
  sConfigInjected.AutoInjectedConv = DISABLE;
  sConfigInjected.InjectedDiscontinuousConvMode = DISABLE;
  sConfigInjected.InjectedOffset = 0;
  if (HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC2_Init 2 */

  /* USER CODE END ADC2_Init 2 */

}

/**
  * @brief SPI1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_SPI1_Init(void)
{

  /* USER CODE BEGIN SPI1_Init 0 */

  /* USER CODE END SPI1_Init 0 */

  /* USER CODE BEGIN SPI1_Init 1 */

  /* USER CODE END SPI1_Init 1 */
  /* SPI1 parameter configuration*/
  hspi1.Instance = SPI1;
  hspi1.Init.Mode = SPI_MODE_MASTER;
  hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
  hspi1.Init.NSS = SPI_NSS_SOFT;
  hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128;
  hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi1.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN SPI1_Init 2 */

  /* USER CODE END SPI1_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Channel2_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel2_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel2_IRQn);
  /* DMA1_Channel3_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel3_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel3_IRQn);

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(MT6701_CS_GPIO_Port, MT6701_CS_Pin, GPIO_PIN_SET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : MT6701_CS_Pin */
  GPIO_InitStruct.Pin = MT6701_CS_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(MT6701_CS_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : LED_Pin */
  GPIO_InitStruct.Pin = LED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED_GPIO_Port, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

// ADC转换完成回调函数
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
    // 读取ADC转换结果并转换为电流值
    if (hadc->Instance == ADC1)
    {
        // 读取ADC1常规通道转换结果
        uint16_t adc_value = HAL_ADC_GetValue(hadc);
        current_a = adc_value * CURRENT_CONV_FACTOR;
    }
    else if (hadc->Instance == ADC2)
    {
        // 读取ADC2常规通道转换结果
        uint16_t adc_value = HAL_ADC_GetValue(hadc);
        current_b = adc_value * CURRENT_CONV_FACTOR;
    }
}

// ADC注入转换完成回调函数
void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc)
{
    // 读取ADC注入通道转换结果并转换为电流值
    if (hadc->Instance == ADC1)
    {
        // 读取ADC1注入通道转换结果
        uint16_t adc_value = HAL_ADCEx_InjectedGetValue(hadc, ADC_INJECTED_RANK_1);
        current_a = adc_value * CURRENT_CONV_FACTOR;
        
        // 重新启动ADC1注入通道转换
        HAL_ADCEx_InjectedStart_IT(&hadc1);
    }
    else if (hadc->Instance == ADC2)
    {
        // 读取ADC2注入通道转换结果
        uint16_t adc_value = HAL_ADCEx_InjectedGetValue(hadc, ADC_INJECTED_RANK_1);
        current_b = adc_value * CURRENT_CONV_FACTOR;
        
        // 重新启动ADC2注入通道转换
        HAL_ADCEx_InjectedStart_IT(&hadc2);
    }
    
    // 计算相电流C (三相电流之和为0)
  current_c = -current_a - current_b;
  
  // 从编码器获取电机角度
  motor_angle = MT6701_GetAngle();
  
  // 执行Clark变换
  clark_transform(current_a, current_b, current_c, &current_alpha, &current_beta);
  
  // 执行Park变换
  park_transform(current_alpha, current_beta, motor_angle, &current_d, &current_q);
    
  // 执行电机控制主循环
  motor_control_loop();
}

// SPI接收完成回调函数
void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
{
    if (hspi->Instance == SPI1)
    {
        static uint8_t crc_error_count = 0;
        const uint8_t MAX_CRC_ERRORS = 3; // �??大CRC错误重试次数
        
        // 设置CS引脚为高电平，结束本次传�??
        HAL_GPIO_WritePin(MT6701_CS_GPIO_Port, MT6701_CS_Pin, GPIO_PIN_SET);
        
        // 计算原始角度�?? (D13-D0)
        uint16_t angle_raw = (mt6701_rx_data[1] >> 2) | (mt6701_rx_data[0] << 6);
        
        // CRC校验，不通过则放弃本次角度数�??
        uint8_t crc_raw = mt6701_rx_data[2] & ((1 << 6) - 1);
        uint32_t crc_data = (mt6701_rx_data[0] << 16 | mt6701_rx_data[1] << 8 | mt6701_rx_data[2]) >> 6;
        
        if (calculate_crc(crc_data) != crc_raw)
        {
            crc_error_count++;
            
            // 如果CRC错误次数超过阈�?�，停止�??段时间再重试
            if (crc_error_count >= MAX_CRC_ERRORS)
            {
                crc_error_count = 0;
                // 不使用HAL_Delay，�?�是使用�??单的软件延时
                for (volatile int i = 0; i < 1000; i++); // �??单的软件延时
            }
            
            // 重新启动DMA传输
            // 不使用HAL_Delay，直接设置CS引脚并启动传�??
            HAL_GPIO_WritePin(MT6701_CS_GPIO_Port, MT6701_CS_Pin, GPIO_PIN_RESET);
            if (HAL_SPI_TransmitReceive_DMA(&hspi1, mt6701_rx_data, mt6701_rx_data, 3) != HAL_OK)
            {
                // 传输启动失败时，确保CS引脚为高电平
                HAL_GPIO_WritePin(MT6701_CS_GPIO_Port, MT6701_CS_Pin, GPIO_PIN_SET);
            }
            return;
        }
        
        // CRC校验成功，重置错误计�??
        crc_error_count = 0;
        
        // 更新全局角度�??
        encoder_angle = 2 * 3.14159265359f * angle_raw / (1 << 14);
        
        // 更新角度跟踪�??
        last_raw_angle = angle_raw;
        
        static float encoder_angle_last = 0;
        static int once = 1;
        
        // 第一次运行时初始化上次角度�??
        if (once)
        {
            once = 0;
            encoder_angle_last = encoder_angle;
        }
        
        float _encoder_angle = encoder_angle;
        
        // 角度差�?�，用于累计多圈逻辑角度
        float diff_angle = cycle_diff(_encoder_angle - encoder_angle_last, 2 * 3.14159265359f);
        encoder_angle_last = _encoder_angle;
        
        // 实现周期操作，将motor_logic_angle转到周期�??
        motor_logic_angle = cycle_diff(motor_logic_angle + diff_angle, position_cycle);
        
        // 不使用HAL_Delay，直接启动下�??次传�??
        // 重新启动下一次DMA传输
        HAL_GPIO_WritePin(MT6701_CS_GPIO_Port, MT6701_CS_Pin, GPIO_PIN_RESET);
        if (HAL_SPI_TransmitReceive_DMA(&hspi1, mt6701_rx_data, mt6701_rx_data, 3) != HAL_OK)
        {
            // 传输启动失败时，确保CS引脚为高电平
            HAL_GPIO_WritePin(MT6701_CS_GPIO_Port, MT6701_CS_Pin, GPIO_PIN_SET);
        }
    }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
